//
//  TransferViewController.m
//  CBT
//
//  Created by Mr.Zhang on 2019/3/11.
//  Copyright © 2019 Mr.Zhang. All rights reserved.
//

#import "TransferViewController.h"
#import "RechargeListViewController.h"
#import "SettingPaymentPwdViewController.h"
#import "ZFPwdView.h"
#import "UserManager.h"
#import "LoginManager.h"
#import "WCQRCodeVC.h"
#import "JHUIAlertView.h"

@interface TransferViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIBarButtonItem *rightBarButtonItem;

@property (weak, nonatomic) IBOutlet UILabel *interestLabel;

@property (weak, nonatomic) IBOutlet UILabel *addressLabel;
@property (weak, nonatomic) IBOutlet UILabel *amountLabel;
@property (weak, nonatomic) IBOutlet UILabel *remarksLabel;

@property (weak, nonatomic) IBOutlet UITextField *addressTextField;
@property (weak, nonatomic) IBOutlet UITextField *amountTextField;
@property (weak, nonatomic) IBOutlet UITextField *remarksTextField;

@property (weak, nonatomic) IBOutlet UILabel *slowLabel;
@property (weak, nonatomic) IBOutlet UILabel *fastLabel;

@property (weak, nonatomic) IBOutlet UIButton *confirmBtn;

@property (weak, nonatomic) IBOutlet UISlider *slider;
@property (weak, nonatomic) IBOutlet UILabel *costLabel;

@property (nonatomic, strong) NoDataView *noNetWorkView;
@property (nonatomic, strong) JHUIAlertView *alertView;
@property (nonatomic, strong) UITextField *rechargeTF;

@property (nonatomic, assign,getter=isloading) BOOL loading;

@end

@implementation TransferViewController

#pragma mark - VC Life

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.tintAdjustmentMode = UIViewTintAdjustmentModeNormal;
}

- (void)viewDidLoad {
    [super viewDidLoad];
        
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = [NSString stringWithFormat:@"%@ %@",self.navTitle,kLocalizedString(@"转账", nil)];
    self.loading = NO;
    
    self.confirmBtn.backgroundColor = DefaultOrangeColor;
   
    [self startLoading];
    
    self.rightBarButtonItem.title    = kLocalizedString(@"转账记录",nil);
    self.amountTextField.placeholder = [NSString stringWithFormat:@"%@ %@", kLocalizedString(@"余额",nil),self.balance];
    
    self.interestLabel.text = kLocalizedString(@"矿工费用",nil);
    self.addressLabel.text  = kLocalizedString(@"收款地址",nil);
    self.amountLabel.text   = kLocalizedString(@"转账数量",nil);
    self.remarksLabel.text  = kLocalizedString([self.navTitle isEqualToString:@"EOS"] ? @"备注" : @"备注(选填)",nil);
    
    self.slowLabel.text = kLocalizedString(@"慢",nil);
    self.fastLabel.text = kLocalizedString(@"快",nil);
    
    [self.confirmBtn setTitle: kLocalizedString(@"确认",nil) forState:(UIControlStateNormal)];
    
    self.slider.zf_trackHeight = 5;
    self.slider.continuous = YES;
    [self.slider setThumbImage:[UIImage imageNamed:@"slider"] forState:UIControlStateHighlighted];
    [self.slider setThumbImage:[UIImage imageNamed:@"slider"] forState:UIControlStateNormal];
    self.slider.minimumTrackTintColor = UIColorFromRGB(0x7889FF);
    self.slider.maximumTrackTintColor = UIColorFromRGB(0xE6E6E6);
    [self.slider addTarget:self action:@selector(sliderDragUp:) forControlEvents:UIControlEventValueChanged];
    
    [self getMinerRate];
}

- (void)getMinerRate
{
    @weak(self)
    [UserManager getMinerRateWithCoinId:self.coinId block:^(NSDictionary *dic, HttpRequestResult result, NSString *msg) {
        [self_weak_ stopLoading];
        [self_weak_.noNetWorkView removeFromSuperview];
        if (result == kHttpRequestResultNormal) {
            self_weak_.slider.minimumValue = [dic[@"slow"]floatValue];
            self_weak_.slider.maximumValue = [dic[@"fast"]floatValue];
            self_weak_.slider.value = [dic[@"defaultValue"]floatValue];
            self_weak_.costLabel.text = [NSString stringWithFormat:@"%@",dic[@"defaultValue"]];
        }
        else {
            [HFStatusView showFailureMessage:kLocalizedString(@"网络异常，请稍后重试", nil)];
            [self_weak_.view addSubview:self_weak_.noNetWorkView];
        }
    }];
}

#pragma mark - UISliderTargetAction
-(void)sliderDragUp:(UISlider *)sender {
    
    NSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:4 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    NSDecimalNumber *aDN = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%.4f",self.slider.value]];
    NSDecimalNumber *resultDN = [aDN decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    [self.costLabel setText:[NSString stringWithFormat:@"%@",resultDN]];
}

- (IBAction)scanCodeBtn:(UIButton *)sender {
    WCQRCodeVC *vc = [[WCQRCodeVC alloc] init];
    vc.textField = self.addressTextField;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - PushRechargeListVC
- (IBAction)rightBarButtonAction:(UIBarButtonItem *)sender {
    
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    RechargeListViewController *vc = [story instantiateViewControllerWithIdentifier:@"rechargeListVC"];
    vc.showListType = 3;
    vc.coinId   = self.coinId;
    vc.coinName = self.navTitle;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSMutableString *s = [NSMutableString stringWithFormat:@"%@",textField.text];
    [s insertString:string atIndex:range.location];
    if (textField.tag == 100 || textField.tag == 102) {
        if ([NSString isBlankString:string]) {
            return YES;
        }
        if (([NSString isContainsEmoji:string] && ![NSString isNineKeyBoard:string]) || (string.isEmoji && ![NSString isNineKeyBoard:string]) || (([NSString hasEmoji:string] && ![NSString isNineKeyBoard:string]))) {
            return NO;
        }
    }
    else {
        if ([s SizeCount] > 4 || ([s isEqualToString:@"."] && [NSString isBlankString:textField.text])) {
            return NO;
        }
        if (![NSString validateNumber:string]) {
            return NO;
        }
        if ([textField.text containsString:@"."] && [string isEqualToString:@"."]) {
            return NO;
        }
    }
    return YES;
}

- (void)closeView {
    [self.alertView dismiss];
    [self.view endEditing:YES];
}

- (void)buttonEvent {
    kPreventRepeatClickTime(1);
    if (self.isloading == NO) {
        self.loading = YES;
    }
    else {
        return;
    }
    @weak(self);
    //校验支付密码
    [UserManager checkPayPassWordWithUserID:[CBTLocalUserManager sharedInstance].userId passWord:self.rechargeTF.text block:^(id data, HttpRequestResult result, NSString *msg) {
        if (result == kHttpRequestResultNormal && [[data[@"data"]objectForKey:@"result"]boolValue] == YES) {
            if ([self.navTitle isEqualToString:@"PC"]) {
                //转账
                [UserManager userDoPCChangeWithUserID:[CBTLocalUserManager sharedInstance].userId coinId:self_weak_.coinId address:self_weak_.addressTextField.text value:self_weak_.amountTextField.text remark:[NSString excludeNullString:self_weak_.remarksTextField.text] feeRatio:self_weak_.costLabel.text password:self.rechargeTF.text block:^(id data, HttpRequestResult result, NSString *msg) {
                    self.loading = NO;
                    [self_weak_ stopLoading];
                    if (result == kHttpRequestResultNormal) {
                        if (self_weak_.transferSuccessBlock != nil) {
                            self_weak_.transferSuccessBlock();
                        }
                        [HFStatusView showSuccessMessage:kLocalizedString(@"提交成功",nil)];
                        [self_weak_.navigationController popViewControllerAnimated:YES];
                    }
                    else {
                        [HFStatusView showFailureMessage:msg];
                    }
                }];
            }
            else {
                //转账
                [UserManager userDoChangeWithUserID:[CBTLocalUserManager sharedInstance].userId coinId:self_weak_.coinId address:self_weak_.addressTextField.text value:self_weak_.amountTextField.text remark:[NSString excludeNullString:self_weak_.remarksTextField.text] feeRatio:self_weak_.costLabel.text block:^(id data, HttpRequestResult result, NSString *msg) {
                    [self_weak_ stopLoading];
                    self.loading = NO;
                    if (result == kHttpRequestResultNormal) {
                        if (self_weak_.transferSuccessBlock != nil) {
                            self_weak_.transferSuccessBlock();
                        }
                        [HFStatusView showSuccessMessage:kLocalizedString(@"提交成功",nil)];
                        [self_weak_.navigationController popViewControllerAnimated:YES];
                    }
                    else {
                        [HFStatusView showFailureMessage:msg];
                    }
                }];
            }
        }
        else {
            self.loading = NO;
            [self_weak_ stopLoading];
            [HFStatusView showFailureMessage:msg];
        }
    }];
}
- (void)payOrder {
    
    kPreventRepeatClickTime(1);

    JHUIAlertConfig *config = [[JHUIAlertConfig alloc] init];
    
    config.title.text  = kLocalizedString(@"校验支付密码", nil);
    config.title.color = UIColorFromRGB(0xff5101);
    config.title.bottomPadding = 100;
    config.dismissWhenTapOut   = NO;
    config.contentViewWidth    = SCREEN_WIDTH*0.8;
    config.contentViewHeight   = 180;
    self.alertView = [[JHUIAlertView alloc] initWithConfig:config];
    
    __weak typeof(self)weakself = self;
    [self.alertView addCustomView:^(JHUIAlertView *alertView, CGRect contentViewRect, CGRect titleLabelRect, CGRect contentLabelRect) {
        
        UIButton *closebtn = [UIButton buttonWithType:UIButtonTypeCustom];
        closebtn.tintColor = [UIColor blackColor];
        [closebtn setImage:[UIImage imageNamed:@"loginClose"] forState:UIControlStateNormal];
        [closebtn addTarget:weakself action:@selector(closeView) forControlEvents:UIControlEventTouchUpInside];
        closebtn.frame = CGRectMake(contentViewRect.size.width-30, 10, 20, 20);
        [alertView.contentView addSubview:closebtn];
        
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(titleLabelRect)+24, contentViewRect.size.width-30, 40)];
        textField.secureTextEntry = YES;
        textField.backgroundColor = UIColorFromRGB(0xEAEAEA);
        textField.keyboardType    = UIKeyboardTypeNumberPad;
        textField.layer.cornerRadius = 5;
        [alertView.contentView addSubview:textField];
        weakself.rechargeTF = textField;
        weakself.rechargeTF.placeholder = kLocalizedString(@"请输入支付密码", nil);
       
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(15, CGRectGetMaxY(textField.frame)+24, contentViewRect.size.width-30, 40);
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        [button setTitle:kLocalizedString(@"确定", nil) forState:0];
        [button setTitleColor:[UIColor whiteColor] forState:0];
        button.layer.cornerRadius = 5;
        button.backgroundColor    = UIColorFromRGB(0xff5001);
        [button addTarget:weakself action:@selector(buttonEvent) forControlEvents:1<<6];
        [alertView.contentView addSubview:button];
        
    }];
    
    [self.view addSubview:self.alertView];
}

#pragma mark - ConfirmAction
- (IBAction)confirmAction:(UIButton *)sender {

    [self.view endEditing:YES];
    if ([NSString isBlankString:self.addressTextField.text]) {
        [HFStatusView showFailureMessage:kLocalizedString(@"请输入收款地址", nil)];
        return;
    }
    else if ([NSString isBlankString:self.amountTextField.text]) {
        [HFStatusView showFailureMessage:kLocalizedString(@"请输入转账数量", nil)];
        return;
    }
    else if ([self.amountTextField.text floatValue] <= 0) {
        [HFStatusView showFailureMessage:kLocalizedString(@"转账数量不能为0", nil)];
        return;
    }
    else if ([self.amountTextField.text floatValue] > [self.balance floatValue]) {
        [HFStatusView showFailureMessage:kLocalizedString(@"转账数量不足", nil)];
        return;
    }
    else if ([self.navTitle isEqualToString:@"EOS"] && [NSString isBlankString:self.remarksTextField.text]) {
        [HFStatusView showFailureMessage:kLocalizedString(@"请输入备注", nil)];
        return;
    }
    else if (![NSString isBlankString:self.remarksTextField.text] && self.remarksTextField.text.length > 15) {
        [HFStatusView showFailureMessage:kLocalizedString(@"备注最多15个字符", nil)];
        return;
    }
    
    @weak(self)
    
    [self startClearBgColorLoading];
    
    //检查是否设置过支付密码、是否实名认证
    NSString *area = [[NSUserDefaults standardUserDefaults] objectForKey:@"area"];
    [LoginManager phoneaAndEmailLoginWithID:[NSString isBlankString:[CBTLocalUserManager sharedInstance].userPhone] ? [CBTLocalUserManager sharedInstance].userEmail : [CBTLocalUserManager sharedInstance].userPhone isPhone:![NSString isBlankString:[CBTLocalUserManager sharedInstance].userPhone]  pwd:HEFANTV_UserPassWord area:area block:^(id data, HttpRequestResult result, NSString *msg) {
        if (result == kHttpRequestResultNormal) {
            
            [[NSUserDefaults standardUserDefaults]setObject:[data[@"data"]objectForKey:@"token"] forKey:HEFANTV_TOKEN];
            [[NSUserDefaults standardUserDefaults]synchronize];
            [[CBTLocalUserManager sharedInstance] saveALLUserInfoDic:data];
            
            [self_weak_ stopLoading];
            
//            if ([[data[@"data"]objectForKey:@"flag"]intValue] != 1) {
//                [HFStatusView showFailureMessage:kLocalizedString(@"请先实名认证", nil)];
//                return;
//            }else
            if ([[data[@"data"]objectForKey:@"status"]intValue] == 0) {
                [HFStatusView showFailureMessage:kLocalizedString(@"请先设置支付密码", nil)];
                UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
                SettingPaymentPwdViewController *registerVC = [story instantiateViewControllerWithIdentifier:@"SettingPaymentID"];
                [self_weak_.navigationController pushViewController:registerVC animated:YES];
                return;
            }
            
            [self payOrder];
        }
        else {
            [HFStatusView showFailureMessage:kLocalizedString(@"网络异常，请稍后重试",nil)];
        }
    }];
}

#pragma mark - Lazy

- (NoDataView *)noNetWorkView {
    if (!_noNetWorkView) {
        @weak(self)
        _noNetWorkView = [[NoDataView alloc]initWithFrame:self.view.bounds type:(ShowType_NoNetWork) clickBlock:^{
            [self_weak_ startClearBgColorLoading];
            [self_weak_ getMinerRate];
        }];
    }
    return _noNetWorkView;
}

@end
